package com.chushula.run;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

 
public class JettyServer {
	static String nginxHome;
	static String mongoHome;
	static String warHome;
	 
	
	static {
		
		try {
			Properties properties = new Properties();
			properties.load(new FileInputStream("C:/d/program/workplace/chushula-launcher/launch.properties"));
			nginxHome = properties.getProperty("nginx.home");
			mongoHome = properties.getProperty("mongo.home");
			warHome = properties.getProperty("war.home");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws Exception {
		// String appHome = System.getenv("chushula_home");
		//System.get
		System.out.println("server starting...");
 		startNginx();
 		startMongo();
 		Thread.sleep(1000);
 	 	runServer();
		 
	}

	private static void startNginx() {
		new Thread() {
			@Override
			public void run() {

				println("killing nginx...");
				ProcessExecutor.execute("taskkill /F /IM nginx.exe > nul");
				println("restart nginx...");
				ProcessExecutor.execute(nginxHome + "/nginx");

			}
		}.start();
	}

	private static void startMongo() {
		new Thread() {
			@Override
			public void run() {

				println("remove mongo lock file");
				new File(mongoHome + "/my_data/mongod.lock").delete();
				println("repair mongo data");
				ProcessExecutor.execute("mongod --repair", mongoHome + "/bin");
				println("start mongo");
				ProcessExecutor.execute("mongod -dbpath="+mongoHome+"/my_data",
						mongoHome+"/bin");

			}
		}.start();
	}

	static void println(Object msg) {
		System.out.println(msg);
	}

	private static void runServer() throws Exception {
		startWebServer();
	}

	private static void startWebServer() throws Exception {
		String serverHome = System.getenv("chushula_war_home");
		if (StringUtils.isBlank(serverHome)) {
			serverHome = warHome;
			System.out.println("chushula_war_home not found");
		}

		int port = 8080;
		Server server = new Server(port);

		WebAppContext webapp = new WebAppContext();
		webapp.setContextPath("/");
		webapp.setWar(serverHome + "/chushula.war");
		server.setHandler(webapp);
		System.out.println("jetty server run at " + 8080);
		server.start();
		server.join();
	}
}
